const host = 'http://www.stardict.com';
const formSubmitURL = 'http://www.stardict.com';
const httpRealm = null;
const history_max = 20;
const history_default = 10;

var prefs = null;

function onPaneLoad(event)
{
  prefs = Components.classes["@mozilla.org/preferences-service;1"]
     			  .getService(Components.interfaces.nsIPrefService).getBranch('extensions.foxydict.');
  let sui = prefs.getBoolPref('saveusrinfo');

  // toggle command
  if (!sui)
  {
    document.getElementById('enableSaveUsrInfo').setAttribute('disabled', 'true');
    return;
  }

  // load saved user login info
  document.getElementById('enableSaveUsrInfo').removeAttribute('disabled');
  let loginmgr = Components.classes['@mozilla.org/login-manager;1']
  			   .getService(Components.interfaces.nsILoginManager);
  var logins = loginmgr.findLogins({}, host, formSubmitURL, httpRealm);
  if (!logins.length)  return;
  document.getElementById('uname').value = logins[0].username;
  document.getElementById('pword').value = logins[0].password;

  // error, saved user info multiple times
  if (logins.length > 1)
  {
    dump('foxydict save_usr_info error!\n');
    for (var i = 1; i < logins.length; i++)
      loginmgr.removeLogin(logins[i]);
  }
};

function onDialogAccept(event)
{
  // extensions.foxydict.saveusrinfo
  if (document.getElementById('saveusrinfo').checked)
  {
    let nsLoginInfo = new Components.Constructor('@mozilla.org/login-manager/loginInfo;1',
                                                  Components.interfaces.nsILoginInfo,
						  'init');
    let uname = document.getElementById('uname').value;
    let pword = document.getElementById('pword').value;
    let loginInfo = new nsLoginInfo(host, formSubmitURL, httpRealm, uname, pword, '', '');

    let loginmgr = Components.classes['@mozilla.org/login-manager;1']
    				     .getService(Components.interfaces.nsILoginManager);
    let logins = loginmgr.findLogins({}, host, formSubmitURL, httpRealm);
    logins.forEach(function(element, index, array) {
                     loginmgr.removeLogin(element);
                   });
    loginmgr.addLogin(loginInfo);
    prefs.setBoolPref('saveusrinfo', 'true');
  }
  else
    prefs.setBoolPref('saveusrinfo', 'false');

  // extensions.foxydict.autologin
  prefs.setBoolPref('autologin', document.getElementById('autologin').checked);

  // extensions.foxydict.historycount
  var hc;
  try
  {
    hc = parseInt(document.getElementById('historycount').value);
    if (hc >= history_max)
      hc = history_default;
  } catch (e)
  {
    hc = history_default;
  } finally
  {
    prefs.setIntPref('historycount', hc);
  }

  // extensions.foxydict.statusbarpinyin
  prefs.setBoolPref('statusbarpinyin', document.getElementById('sbpinyin').checked);
};
